// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    console.log("DOM fully loaded and parsed");

    // 添加页面加载动画
    const loader = document.querySelector('.page-loader');
    if (loader) {
        setTimeout(function() {
            document.body.classList.add('loaded');
            loader.style.display = 'none';
        }, 300);
    }
    
    // 导航栏滚动效果
    const nav = document.querySelector('nav');
    if (nav) {
        window.addEventListener('scroll', function() {
            if (window.scrollY > 50) {
                nav.classList.add('scrolled');
            } else {
                nav.classList.remove('scrolled');
            }
        });
    }
    
    // 移动端菜单切换
    const menuToggle = document.querySelector('.menu-toggle');
    const mainNav = document.querySelector('.main-nav');
    
    if (menuToggle && mainNav) {
        menuToggle.addEventListener('click', function() {
            mainNav.classList.toggle('active');
            menuToggle.classList.toggle('active');
            
            // 防止菜单打开时页面滚动
            document.body.style.overflow = mainNav.classList.contains('active') ? 'hidden' : '';
        });
        
        // 点击菜单外区域关闭菜单
        document.addEventListener('click', function(event) {
            if (!menuToggle.contains(event.target) && !mainNav.contains(event.target) && mainNav.classList.contains('active')) {
                mainNav.classList.remove('active');
                menuToggle.classList.remove('active');
                document.body.style.overflow = '';
            }
        });
    }

    // 增强轮播图功能
    const carousel = document.querySelector('.carousel');
    if (carousel) {
        const carouselSlides = carousel.querySelectorAll('.carousel-slide');
        const prevBtn = carousel.querySelector('.carousel-prev');
        const nextBtn = carousel.querySelector('.carousel-next');
        const indicators = carousel.querySelectorAll('.carousel-indicator');
        
        if (carouselSlides.length > 0) {
            let currentSlide = 0;
            const slideCount = carouselSlides.length;
            let autoSlideInterval;
            let progressBar;
            
            // 创建进度条
            function createProgressBar() {
                progressBar = document.createElement('div');
                progressBar.className = 'carousel-progress';
                carousel.appendChild(progressBar);
            }
            
            // 更新进度条
            function updateProgressBar() {
                if (progressBar) {
                    progressBar.style.width = '0%';
                    setTimeout(() => {
                        progressBar.style.width = '100%';
                    }, 50);
                }
            }
            
            // 显示当前幻灯片
            function showSlide(index) {
                carouselSlides.forEach(slide => slide.classList.remove('active'));
                indicators.forEach(indicator => indicator.classList.remove('active'));
                
                carouselSlides[index].classList.add('active');
                indicators[index].classList.add('active');
                
                updateProgressBar();
            }
            
            // 下一张幻灯片
            function nextSlide() {
                currentSlide = (currentSlide + 1) % slideCount;
                showSlide(currentSlide);
            }
            
            // 上一张幻灯片
            function prevSlide() {
                currentSlide = (currentSlide - 1 + slideCount) % slideCount;
                showSlide(currentSlide);
            }
            
            // 添加事件监听器
            if (nextBtn) {
                nextBtn.addEventListener('click', function() {
                    nextSlide();
                    resetAutoSlide();
                });
            }
            
            if (prevBtn) {
                prevBtn.addEventListener('click', function() {
                    prevSlide();
                    resetAutoSlide();
                });
            }
            
            // 为指示器添加点击事件
            indicators.forEach((indicator, index) => {
                indicator.addEventListener('click', () => {
                    currentSlide = index;
                    showSlide(currentSlide);
                    resetAutoSlide();
                });
            });
            
            // 开始自动轮播
            function startAutoSlide() {
                autoSlideInterval = setInterval(nextSlide, 3000);
            }
            
            // 重置自动轮播
            function resetAutoSlide() {
                clearInterval(autoSlideInterval);
                startAutoSlide();
            }
            
            // 鼠标悬停时暂停轮播
            carousel.addEventListener('mouseenter', function() {
                clearInterval(autoSlideInterval);
                if (progressBar) progressBar.style.transition = 'none';
            });
            
            // 鼠标离开时恢复轮播
            carousel.addEventListener('mouseleave', function() {
                if (progressBar) progressBar.style.transition = 'width 3s linear';
                startAutoSlide();
                updateProgressBar();
            });
            
            // 触摸事件支持
            let touchStartX = 0;
            let touchEndX = 0;
            
            carousel.addEventListener('touchstart', function(e) {
                touchStartX = e.changedTouches[0].screenX;
                clearInterval(autoSlideInterval);
                if (progressBar) progressBar.style.transition = 'none';
            }, { passive: true });
            
            carousel.addEventListener('touchend', function(e) {
                touchEndX = e.changedTouches[0].screenX;
                handleSwipe();
                if (progressBar) progressBar.style.transition = 'width 3s linear';
                startAutoSlide();
                updateProgressBar();
            }, { passive: true });
            
            function handleSwipe() {
                const swipeThreshold = 50;
                if (touchEndX < touchStartX - swipeThreshold) {
                    nextSlide();
                } else if (touchEndX > touchStartX + swipeThreshold) {
                    prevSlide();
                }
            }
            
            // 初始化轮播图
            createProgressBar();
            showSlide(0);
            startAutoSlide();
        }
    }

    // 滚动动画效果
    // const scrollElements = document.querySelectorAll('.fade-in, .slide-in-left, .slide-in-right');
    
    const elementInView = (el, dividend = 1) => {
        const elementTop = el.getBoundingClientRect().top;
        return (
            elementTop <= (window.innerHeight || document.documentElement.clientHeight) / dividend
        );
    };
    
    const displayScrollElement = (element) => {
        element.classList.add('scrolled');
    };
    
    const hideScrollElement = (element) => {
        element.classList.remove('scrolled');
    };
    
    const handleScrollAnimation = () => {
        const scrollElements = document.querySelectorAll('.fade-in, .slide-in-left, .slide-in-right');
        scrollElements.forEach((el) => {
            if (elementInView(el, 1.25)) {
                displayScrollElement(el);
            } else {
                hideScrollElement(el);
            }
        });
    };
    
    window.addEventListener('scroll', handleScrollAnimation);
    handleScrollAnimation();

    // 返回顶部按钮
    const backToTopBtn = document.querySelector('.back-to-top');
    
    if (backToTopBtn) {
        window.addEventListener('scroll', () => {
            if (window.pageYOffset > 300) {
                backToTopBtn.classList.add('show');
            } else {
                backToTopBtn.classList.remove('show');
            }
        });
        
        backToTopBtn.addEventListener('click', () => {
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        });
    } else {
        // 如果按钮不存在，创建一个
        createBackToTopButton();
    }
    
    // 创建返回顶部按钮
    function createBackToTopButton() {
        const backToTopButton = document.createElement('button');
        backToTopButton.className = 'back-to-top';
        backToTopButton.innerHTML = '<i class="fas fa-arrow-up"></i>';
        document.body.appendChild(backToTopButton);
        
        backToTopButton.addEventListener('click', function() {
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        });
        
        window.addEventListener('scroll', function() {
            if (window.pageYOffset > 300) {
                backToTopButton.classList.add('show');
            } else {
                backToTopButton.classList.remove('show');
            }
        });
    }

    // 浮动导航
    console.log("查找浮动导航元素");
    const floatNavToggle = document.getElementById('floatNavToggle');
    const floatNavMenu = document.getElementById('floatNavMenu');
    
    if (floatNavToggle && floatNavMenu) {
        console.log("找到浮动导航元素，正在添加事件监听器");
        floatNavToggle.addEventListener('click', function() {
            floatNavMenu.classList.toggle('show');
            floatNavToggle.classList.toggle('active');
        });
    } else {
        console.log("未找到浮动导航菜单或其切换按钮。");
    }

    // 顶部快速导航栏
    const topQuickNav = document.querySelector('.top-quick-nav');
    
    if (topQuickNav) {
        // 滚动时添加阴影效果
        window.addEventListener('scroll', function() {
            if (window.scrollY > 10) {
                topQuickNav.classList.add('scrolled');
            } else {
                topQuickNav.classList.remove('scrolled');
            }
        });
        
        // 设置当前页面对应的导航项为活动状态
        const currentPath = window.location.pathname;
        const topNavLinks = topQuickNav.querySelectorAll('a');
        
        topNavLinks.forEach(link => {
            const linkPath = link.getAttribute('href');
            if (currentPath.endsWith(linkPath)) {
                link.classList.add('active');
            } else if (currentPath.endsWith('/') && linkPath === 'index.html') {
                link.classList.add('active');
            } else {
                link.classList.remove('active');
            }
        });
    }

    // FAQ展开/收起功能
    const faqQuestions = document.querySelectorAll('.faq-question');
    
    faqQuestions.forEach(question => {
        question.addEventListener('click', function() {
            const answer = this.nextElementSibling;
            const icon = this.querySelector('.toggle-icon i');
            
            // 关闭其他所有FAQ
            faqQuestions.forEach(item => {
                if (item !== question) {
                    const otherAnswer = item.nextElementSibling;
                    const otherIcon = item.querySelector('.toggle-icon i');
                    
                    if (otherAnswer.style.maxHeight) {
                        otherAnswer.style.maxHeight = null;
                        if (otherIcon) {
                            otherIcon.classList.remove('fa-minus');
                            otherIcon.classList.add('fa-plus');
                        }
                    }
                }
            });
            
            // 切换当前FAQ的显示/隐藏
            if (answer.style.maxHeight) {
                answer.style.maxHeight = null;
                if (icon) {
                    icon.classList.remove('fa-minus');
                    icon.classList.add('fa-plus');
                }
            } else {
                answer.style.maxHeight = answer.scrollHeight + 'px';
                if (icon) {
                    icon.classList.remove('fa-plus');
                    icon.classList.add('fa-minus');
                }
            }
        });
    });

    // 平滑滚动到锚点
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();
            
            const targetId = this.getAttribute('href');
            if (targetId === '#') return;
            
            const targetElement = document.querySelector(targetId);
            if (targetElement) {
                // 考虑固定导航栏的高度
                const headerHeight = document.querySelector('header').offsetHeight;
                const elementPosition = targetElement.getBoundingClientRect().top + window.pageYOffset;
                const offsetPosition = elementPosition - headerHeight - 20;
                
                window.scrollTo({
                    top: offsetPosition,
                    behavior: 'smooth'
                });
                
                // 如果在移动端且菜单打开，关闭菜单
                if (window.innerWidth < 768 && mainNav && mainNav.classList.contains('active')) {
                    mainNav.classList.remove('active');
                    menuToggle.classList.remove('active');
                    document.body.style.overflow = '';
                }
            }
        });
    });
    
    // 图片延迟加载
    if ('IntersectionObserver' in window) {
        const lazyImages = document.querySelectorAll('img[data-src]');
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    img.src = img.dataset.src;
                    img.removeAttribute('data-src');
                    imageObserver.unobserve(img);
                }
            });
        });
        
        lazyImages.forEach(img => {
            imageObserver.observe(img);
        });
    }
    
    // 表单验证
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        if (form.querySelector('[required]')) {
            form.addEventListener('submit', function(e) {
                let isValid = true;
                const requiredFields = form.querySelectorAll('[required]');
                
                requiredFields.forEach(field => {
                    if (!field.value.trim()) {
                        e.preventDefault();
                        isValid = false;
                        field.classList.add('input-error');
                        
                        // 添加错误提示
                        const existingError = field.parentNode.querySelector('.error-message');
                        if (!existingError) {
                            const errorMsg = document.createElement('div');
                            errorMsg.className = 'error-message';
                            errorMsg.textContent = '此字段不能为空';
                            field.parentNode.appendChild(errorMsg);
                        }
                    } else {
                        field.classList.remove('input-error');
                        const existingError = field.parentNode.querySelector('.error-message');
                        if (existingError) {
                            existingError.remove();
                        }
                    }
                });
                
                return isValid;
            });
        }
    });

    // 自动高亮当前导航项
    var path = window.location.pathname.split('/').pop();
    if (!path) path = 'index.html'; // 默认首页
    var navLinks = document.querySelectorAll(
        '.main-nav a, .float-nav-menu a, .top-quick-nav a'
    );
    navLinks.forEach(function (link) {
        var href = link.getAttribute('href').split('?')[0].split('#')[0];
        if (href === path) {
            link.classList.add('active');
        } else {
            link.classList.remove('active');
        }
    });

    // 点击外部区域关闭浮动菜单
    document.addEventListener('click', function(event) {
        if (floatNavMenu && floatNavToggle && floatNavMenu.classList.contains('show')) {
            // 确保点击的不是切换按钮自身
            if (!floatNavToggle.contains(event.target)) {
                console.log('点击菜单外部区域，关闭菜单。');
                floatNavMenu.classList.remove('show');
                floatNavToggle.classList.remove('show');
            }
        }
    });

    // 处理用户认证状态
    const token = localStorage.getItem('token');
}); 